<template>
  <div class="page-container">
    <van-nav-bar
      :title="isEdit ? '编辑规则' : '新建规则'"
      left-arrow
      @click-left="router.back()"
    >
      <template #right>
        <van-button size="small" type="primary" @click="saveRule">保存</van-button>
      </template>
    </van-nav-bar>

    <div class="content">
      <van-form @submit="saveRule">
        <!-- 基本信息 -->
        <van-cell-group inset title="基本信息">
          <van-field
            v-model="form.ruleName"
            name="ruleName"
            label="规则名称"
            placeholder="请输入规则名称"
            :rules="[{ required: true, message: '请输入规则名称' }]"
          />

          <van-field
            v-model="form.ruleCode"
            name="ruleCode"
            label="规则编码"
            placeholder="自动生成"
            readonly
          />

          <van-field
            v-model="groupName"
            name="groupId"
            label="所属分组"
            placeholder="请选择分组"
            readonly
            is-link
            @click="showGroupPicker = true"
            :rules="[{ required: true, message: '请选择所属分组' }]"
          />

          <van-field
            v-model="form.effectiveStartDate"
            name="effectiveStartDate"
            label="有效开始时间"
            placeholder="请选择日期"
            readonly
            is-link
            @click="showDatePicker = true"
            :rules="[{ required: true, message: '请选择有效开始时间' }]"
          />

          <van-field
            v-model="form.rulePriority"
            name="rulePriority"
            label="规则优先级"
            placeholder="数字越小优先级越高"
            type="number"
          />

          <van-field
            v-model="form.applicableYears"
            name="applicableYears"
            label="适用年限"
            placeholder="如：2024"
          />

          <van-field
            v-model="form.contactEmail"
            name="contactEmail"
            label="联系邮箱"
            placeholder="请输入联系邮箱"
            type="email"
          />
        </van-cell-group>

        <!-- 规则描述 -->
        <van-cell-group inset title="规则描述">
          <van-field
            v-model="form.ruleDescription"
            name="ruleDescription"
            label="规则描述"
            type="textarea"
            placeholder="请输入规则描述"
            rows="3"
          />
        </van-cell-group>

        <!-- 业务字段配置 -->
        <van-cell-group inset title="业务字段配置">
          <van-cell title="字段配置" is-link @click="openBusinessFieldsDialog">
            <template #value>
              <span v-if="form.businessFields && form.businessFields.length > 0">
                已配置 {{ form.businessFields.length }} 个字段
              </span>
              <span v-else class="placeholder">点击配置</span>
            </template>
          </van-cell>
        </van-cell-group>

        <!-- 参数表配置 -->
        <van-cell-group inset title="参数表配置">
          <van-cell title="参数表关联" is-link @click="openParameterTablesDialog">
            <template #value>
              <span v-if="form.parameterTables && form.parameterTables.length > 0">
                已配置 {{ form.parameterTables.length }} 个参数表
              </span>
              <span v-else class="placeholder">点击配置</span>
            </template>
          </van-cell>
        </van-cell-group>

        <!-- 过滤条件 -->
        <van-cell-group inset title="过滤条件">
          <van-cell title="数据过滤" is-link @click="openFilterConditionsDialog">
            <template #value>
              <span v-if="hasFilterConditions">已配置过滤条件</span>
              <span v-else class="placeholder">点击配置</span>
            </template>
          </van-cell>
        </van-cell-group>
      </van-form>
    </div>

    <!-- 分组选择器 -->
    <van-popup v-model:show="showGroupPicker" position="bottom">
      <van-picker
        :columns="groupOptions"
        @confirm="onGroupConfirm"
        @cancel="showGroupPicker = false"
      />
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        v-model="currentDate"
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>

    <!-- 业务字段配置弹窗 -->
    <van-dialog
      v-model:show="showBusinessFieldsDialog"
      title="业务字段配置"
      show-cancel-button
      @confirm="saveBusinessFields"
      class="field-config-dialog"
    >
      <div class="dialog-content">
        <div v-for="(field, index) in businessFieldsTemp" :key="index" class="field-item">
          <van-field v-model="field.fieldName" label="字段名" placeholder="如：entry_id" />
          <van-field v-model="field.description" label="字段描述" placeholder="如：报关单号" />
          <van-field v-model="field.fieldType" label="字段类型" placeholder="如：string" />
          <van-checkbox v-model="field.required">必填字段</van-checkbox>
          <van-field v-model="field.validationRule" label="校验规则" placeholder="如：NOT_NULL" />
          <van-button size="mini" type="danger" @click="removeBusinessField(index)">删除</van-button>
        </div>
        <van-button type="primary" size="small" @click="addBusinessField">添加字段</van-button>
      </div>
    </van-dialog>

    <!-- 参数表配置弹窗 -->
    <van-dialog
      v-model:show="showParameterTablesDialog"
      title="参数表配置"
      show-cancel-button
      @confirm="saveParameterTables"
      class="field-config-dialog"
    >
      <div class="dialog-content">
        <div v-for="(table, index) in parameterTablesTemp" :key="index" class="field-item">
          <van-field v-model="table.tableCode" label="参数表编码" placeholder="如：TRADE_MODE" />
          <van-field v-model="table.tableName" label="参数表名称" placeholder="如：贸易方式参数表" />
          <van-field v-model="table.keyField" label="关键字段" placeholder="如：trade_mode_code" />
          <van-field v-model="table.valueField" label="值字段" placeholder="如：trade_mode_name" />
          <van-field v-model="table.validationType" label="校验类型" placeholder="如：EXISTS" />
          <van-button size="mini" type="danger" @click="removeParameterTable(index)">删除</van-button>
        </div>
        <van-button type="primary" size="small" @click="addParameterTable">添加参数表</van-button>
      </div>
    </van-dialog>

    <!-- 过滤条件配置弹窗 -->
    <van-dialog
      v-model:show="showFilterConditionsDialog"
      title="过滤条件配置"
      show-cancel-button
      @confirm="saveFilterConditions"
    >
      <div class="dialog-content">
        <van-field
          v-model="filterConditionsText"
          type="textarea"
          rows="6"
          placeholder='请输入JSON格式的过滤条件，如：{"customs_code": ["0100", "0200"]}'
        />
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { dataControlApi } from '@/api'

const router = useRouter()
const route = useRoute()

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 响应式数据
const loading = ref(false)
const showGroupPicker = ref(false)
const showDatePicker = ref(false)
const showBusinessFieldsDialog = ref(false)
const showParameterTablesDialog = ref(false)
const showFilterConditionsDialog = ref(false)

const currentDate = ref(['2024', '01', '01'])
const groupName = ref('')
const filterConditionsText = ref('')

// 表单数据
const form = reactive({
  id: null,
  ruleName: '',
  ruleCode: '',
  groupId: null,
  effectiveStartDate: '',
  rulePriority: 1,
  applicableYears: '2024',
  contactEmail: '',
  ruleDescription: '',
  businessFields: [],
  parameterTables: [],
  filterConditions: {}
})

// 临时数据
const businessFieldsTemp = ref([])
const parameterTablesTemp = ref([])

// 分组选项
const groupOptions = ref([])

// 计算属性
const hasFilterConditions = computed(() => {
  return form.filterConditions && Object.keys(form.filterConditions).length > 0
})

// 加载分组选项
const loadGroupOptions = async () => {
  try {
    const groups = await dataControlApi.getGroupTree()
    groupOptions.value = flattenGroups(groups)
  } catch (error) {
    showToast('加载分组失败: ' + error.message)
  }
}

// 扁平化分组数据
const flattenGroups = (groups, prefix = '') => {
  const result = []
  groups.forEach(group => {
    const text = prefix ? `${prefix} > ${group.groupName}` : group.groupName
    result.push({ text, value: group.id })

    if (group.children && group.children.length > 0) {
      result.push(...flattenGroups(group.children, text))
    }
  })
  return result
}

// 加载规则详情（编辑模式）
const loadRule = async () => {
  if (!route.params.id) return

  loading.value = true
  try {
    const rule = await dataControlApi.getRuleDetail(route.params.id)

    // 填充表单数据
    Object.assign(form, rule)

    // 设置分组名称
    const groupOption = groupOptions.value.find(g => g.value === rule.groupId)
    if (groupOption) {
      groupName.value = groupOption.text
    }

    // 设置过滤条件文本
    if (rule.filterConditions) {
      filterConditionsText.value = JSON.stringify(rule.filterConditions, null, 2)
    }
  } catch (error) {
    showToast('加载失败: ' + error.message)
    router.back()
  } finally {
    loading.value = false
  }
}

// 分组选择确认
const onGroupConfirm = ({ selectedOptions }) => {
  form.groupId = selectedOptions[0].value
  groupName.value = selectedOptions[0].text
  showGroupPicker.value = false
}

// 日期选择确认
const onDateConfirm = () => {
  form.effectiveStartDate = currentDate.value.join('-')
  showDatePicker.value = false
}

// 添加业务字段
const addBusinessField = () => {
  businessFieldsTemp.value.push({
    fieldName: '',
    fieldType: 'string',
    description: '',
    required: false,
    validationRule: ''
  })
}

// 删除业务字段
const removeBusinessField = (index) => {
  businessFieldsTemp.value.splice(index, 1)
}

// 保存业务字段
const saveBusinessFields = () => {
  form.businessFields = [...businessFieldsTemp.value]
  showBusinessFieldsDialog.value = false
}

// 添加参数表
const addParameterTable = () => {
  parameterTablesTemp.value.push({
    tableCode: '',
    tableName: '',
    keyField: '',
    valueField: '',
    validationType: 'EXISTS'
  })
}

// 删除参数表
const removeParameterTable = (index) => {
  parameterTablesTemp.value.splice(index, 1)
}

// 保存参数表
const saveParameterTables = () => {
  form.parameterTables = [...parameterTablesTemp.value]
  showParameterTablesDialog.value = false
}

// 保存过滤条件
const saveFilterConditions = () => {
  try {
    if (filterConditionsText.value.trim()) {
      form.filterConditions = JSON.parse(filterConditionsText.value)
    } else {
      form.filterConditions = {}
    }
    showFilterConditionsDialog.value = false
  } catch (error) {
    showToast('JSON格式错误')
  }
}

// 打开业务字段配置弹窗
const openBusinessFieldsDialog = () => {
  businessFieldsTemp.value = form.businessFields ? [...form.businessFields] : []
  showBusinessFieldsDialog.value = true
}

// 打开参数表配置弹窗
const openParameterTablesDialog = () => {
  parameterTablesTemp.value = form.parameterTables ? [...form.parameterTables] : []
  showParameterTablesDialog.value = true
}

// 打开过滤条件配置弹窗
const openFilterConditionsDialog = () => {
  if (form.filterConditions && Object.keys(form.filterConditions).length > 0) {
    filterConditionsText.value = JSON.stringify(form.filterConditions, null, 2)
  } else {
    filterConditionsText.value = ''
  }
  showFilterConditionsDialog.value = true
}

// 保存规则
const saveRule = async () => {
  // 基本验证
  if (!form.ruleName.trim()) {
    showToast('请输入规则名称')
    return
  }

  if (!form.groupId) {
    showToast('请选择所属分组')
    return
  }

  if (!form.effectiveStartDate) {
    showToast('请选择有效开始时间')
    return
  }

  loading.value = true
  try {
    if (isEdit.value) {
      await dataControlApi.updateRule(form.id, form)
      showToast('更新成功')
    } else {
      await dataControlApi.createRule(form)
      showToast('创建成功')
    }
    router.back()
  } catch (error) {
    showToast('保存失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 监听业务字段弹窗显示
const watchBusinessFieldsDialog = () => {
  if (showBusinessFieldsDialog.value) {
    businessFieldsTemp.value = form.businessFields ? [...form.businessFields] : []
  }
}

// 监听参数表弹窗显示
const watchParameterTablesDialog = () => {
  if (showParameterTablesDialog.value) {
    parameterTablesTemp.value = form.parameterTables ? [...form.parameterTables] : []
  }
}

// 监听过滤条件弹窗显示
const watchFilterConditionsDialog = () => {
  if (showFilterConditionsDialog.value) {
    if (form.filterConditions && Object.keys(form.filterConditions).length > 0) {
      filterConditionsText.value = JSON.stringify(form.filterConditions, null, 2)
    } else {
      filterConditionsText.value = ''
    }
  }
}

onMounted(async () => {
  await loadGroupOptions()
  if (isEdit.value) {
    await loadRule()
  }

  // 监听弹窗状态变化
  watch(showBusinessFieldsDialog, watchBusinessFieldsDialog)
  watch(showParameterTablesDialog, watchParameterTablesDialog)
  watch(showFilterConditionsDialog, watchFilterConditionsDialog)
})
</script>

<style scoped>
.content {
  padding: 16px;
}

.placeholder {
  color: #969799;
  font-size: 14px;
}

.field-config-dialog {
  width: 90%;
}

.dialog-content {
  padding: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.field-item {
  padding: 12px;
  border: 1px solid #ebedf0;
  border-radius: 8px;
  margin-bottom: 12px;
}

.field-item .van-field {
  margin-bottom: 8px;
}

.van-cell-group {
  margin-bottom: 16px;
}
</style>
